package com.ugoodtech.mdcc.client.controller;

import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.core.domain.AnswerDic;
import com.ugoodtech.mdcc.core.repository.AnswerDicRepository;
import com.ugoodtech.mdcc.core.utils.AliServiceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Api(description = "题目字典")
@Controller
@RequestMapping("/answerDirc")
public class AnswerDircController {

    @Value("${oss.bucket.name}")
    private String ossBucketName;
    @Value("${oss.photo.bucket.name}")
    private String ossPhotoBucketName;

    private static final Logger logger = LoggerFactory.getLogger(AnswerDircController.class);

    @Autowired
    private AnswerDicRepository answerDicRepository;

    @ApiOperation("更新字典图片")
    @RequestMapping(value = "/updateAnswerDicPhoto", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse updateAnswerDir(Long answerDicId, MultipartFile file) {
        AnswerDic answerDic = answerDicRepository.findOne(answerDicId);
        if (answerDic == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此字典");
        }

        Long time = System.currentTimeMillis();
        logger.info("原始文件名" + file.getOriginalFilename());
        String dir = "backend/answer/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
        if (dir.indexOf(".") == -1) {
            dir += ".jpg";
            logger.info("原文件名没有后缀");
        }
        logger.info("文件路径为" + dir);
        try {
            AliServiceUtil.putObject(file.getInputStream(), dir, ossPhotoBucketName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info(System.currentTimeMillis() - time + "");

        answerDic.setPhoto(dir);
        answerDicRepository.save(answerDic);
        return JsonResponse.successResponseWithData("更新照片成功" + answerDicId);
    }

}
